import { Commit, Dispatch, Module, Action } from "vuex";
import {
  Menu,
  SystemConf,
  State,
  LoginStatus,
  PutAuthUserModpwd,
  GetDatapowerRoles,
  LoginInfo,
  LoginByTokenParams,
  LoginUserInfo,
} from "./interface";

export * from "./interface";

import storage, {
  saveTokenToLocal,
  deleteTokenFormLocal,
  getTokenFormLocal,
} from "@/utils/Storage";
import { EventBus, jsonTree } from "feok-lib";

import { postApiAuthLogin, getApiUserInfo, putApiUserPassword } from "@/model";

export const LOGIN_SUCCESS = "LOGIN_SUCCESS"; // 登录成功
export const MENUS_DONE = "MENUS_DONE"; // 菜单
export const SYSTEM_CONF_DONE = "SYSTEM_CONF_DONE";

export const RESET_PASS = "RESET_PASS"; // 是否是初始密码
export const LOGIN_USER_INFO = "LOGIN_USER_INFO"; // 更新登录用户信息

const TOKEN_KEY = "token"; // token key

/**
 * 验证函数： 是否已经登录
 * @returns {boolean} - true:已经登录； false: 未登录
 */
const isLogined = (): boolean => {
  if (process.env.VUE_APP_TOKEN_PATTERN === "session") {
    return !!storage.session.get(TOKEN_KEY);
  } else {
    return !!storage.get(TOKEN_KEY);
  }
};

const state = (): State => ({
  id: "",
  token: getTokenFormLocal() || "",
  account: "",
  name: "",
  logined: isLogined(),
  loginFailure: false,
  lastLoginTime: "",
  roles: [],
  menus: [],
  systemConf: [],
  reset_pass: false,
  mobile: "",
  depotManagerFlg: false
});

const mutations = {
  [LOGIN_SUCCESS](sta: State, payload: LoginStatus) {
    sta.logined = true;
    sta.loginFailure = true;
    sta.token = payload.token;
    saveTokenToLocal(payload.token);
  },
  [RESET_PASS](sta: State, payload: boolean) {
    sta.reset_pass = payload;
  },
  [MENUS_DONE](sta: State, payload: Menu[]) {
    sta.menus = payload;
  },
  [SYSTEM_CONF_DONE](sta: State, payload: SystemConf[]) {
    sta.systemConf = payload;
  },
  [LOGIN_USER_INFO](
    sta: State,
    payload: LoginUserInfo
  ) {
    const {
      id,
      name
    } = payload;

    sta.id = id;
    sta.name = name;
  }
};

const actions = {
  /**
   * 系统登录
   */
  async loginByUsername(
    context: { commit: Commit; diapatch: Dispatch },
    payload: LoginInfo
  ) {
    const data = await postApiAuthLogin({
      name: payload.username,
      password: payload.password
      // sessionId: payload.sessionId,
      // token: payload.token,
      // sig: payload.sig,
      // scene: payload.scene,
      // aliAfsFlg: payload.checkflg,
    });
    context.commit(LOGIN_SUCCESS, {
      token: data
    });
  },

  /**
   *
   */
  async getMenus(context: { commit: Commit, state: State }) {
    // const data = await getWebAuthUserMenuList();
    // const optionList = data.option_list || [];
    const data = require("../../menu.json");
    const menus = data.menu_list.map((item: any) => ({
      id: item.id,
      pid: item.parent_id,
      name: item.name,
      path: `${item.url}`,
      icon: item.icon_url || "",
      status: ""
    }));
    context.commit(MENUS_DONE, jsonTree(menus, {
    }));
    // context.commit(SYSTEM_CONF_DONE, optionList);
  },

  /**
   * 拉取登录用户信息
   */
  async getLoginUserInfo(context: { commit: Commit; dispatch: Dispatch; state: State }) {
    const data = await getApiUserInfo();
    context.commit(LOGIN_USER_INFO, data);
  },

  /**
   * 退出
   * @param context
   */
  async logout(context: { commit: Commit; dispatch: Dispatch }) {
    EventBus.$emit("ws/stopMissionTask"); // 关闭推送
    return deleteTokenFormLocal();
  },

  /**
   * 用户修改密码
   */
  async putAuthUserModpwd(
    context: { commit: Commit; diapatch: Dispatch },
    payload: PutAuthUserModpwd
  ) {
    const obj = await putApiUserPassword(payload);
    return obj;
  },

  /**
   * 根据SS\SR类型获取角色权限列表
   */
  async getDatapowerRoles({ }, payload: GetDatapowerRoles) {
    // const data = await getDatapowerRoles(payload);
    // return data;
  },

  loginByToken(context: { commit: Commit; dispatch: Dispatch }, payload: LoginByTokenParams) {
    context.commit(LOGIN_SUCCESS, {
      token: payload.token
    });
  }
};

const userModule = {
  namespaced: true,
  state,
  mutations,
  actions
};

export default userModule;
